import "../../../utils/dotenv";
import { ConnectionOptions, getConnectionOptions, DataSource } from "typeorm";
import { Service } from "typedi";

import User from "./entity/User";

@Service()
export default class MysqlManager {
  private dataSource! : Promise<DataSource>;

  async initialize () : Promise<void> {
    const connectionOptions = await getConnectionOptions();
    const config = Object.assign(
      connectionOptions,
      {
        database: process.env.DB_NAME,
        host: process.env.DB_HOST,
        port: process.env.DB_PORT,
        username: process.env.DB_USER,
        password: process.env.DB_PASS,
        entities: [
          User,
        ],
      },
    ) as ConnectionOptions;
    this.dataSource = new DataSource(config).initialize();
  }

  async dispose () : Promise<void> {
    await (await this.dataSource).destroy();
  }

  getConnection () : Promise<DataSource> {
    return this.dataSource;
  }
}
